package com.crane.app.web.controller;


import com.crane.common.core.utils.BaseContextHandler;
import com.crane.common.core.utils.CollectionUtil;
import com.crane.oss.app.bean.resp.AppStudentInfo;
import com.crane.oss.app.bean.resp.AppUserResp;
import com.crane.oss.app.service.AppUserService;
import com.crane.oss.school.bean.resp.TeacherResp;
import com.crane.oss.school.service.StudentService;
import com.crane.oss.school.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;


@Controller
@Slf4j
public class BaseAppController {

    @Autowired
    AppUserService appUserService;

    @Autowired
    TeacherService teacherService;

    @Autowired
    StudentService studentService;




    protected Long getUserId() {
        return  BaseContextHandler.getUserId();
    }

    protected Long getPartyId() {
        Long partyId = null;
        Long userId=getUserId();
        if(null ==userId){
            return partyId;
        }
        AppUserResp appUserResp=appUserService.queryAppUser(userId);
        if(null == appUserResp.getBeforeType()){
            if(appUserResp.getUserType().equals(1)){
                partyId = getPartyIdTeacher(userId);
            }else{
                partyId = getPartyIdByStudent(userId, appUserResp);
            }
        }else {
            if(appUserResp.getBeforeType().equals(1)){
                partyId = getPartyIdTeacher(userId);
            }else{
                partyId = getPartyIdByStudent(userId, appUserResp);
            }
        }
        return partyId;
    }

    private Long getPartyIdTeacher(Long userId) {
        TeacherResp teacherResp=teacherService.queryTeacherByAppUserId(userId);
        if(null != teacherResp){
            return teacherResp.getPartyId();
        }
        return null;
    }

    private Long getPartyIdByStudent(Long userId, AppUserResp appUserResp) {
        List<AppStudentInfo> studentInfoList=studentService.appQueryStudentInfo(userId);
        if(CollectionUtil.isNotEmpty(studentInfoList)){
            if(null == appUserResp.getBeforeStudent()){
                return studentInfoList.get(0).getPartyId();
            }else{
                for(AppStudentInfo appStudentInfo : studentInfoList){
                    if(appStudentInfo.getStudentId().equals(appUserResp.getBeforeStudent())){
                        return appStudentInfo.getPartyId();
                    }
                }
                return studentInfoList.get(0).getPartyId();
            }
        }
        return null;
    }
}
